package com.yzqp.common.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Bean工具类,使用fastJson进行转换
 */
public class BeanUtil {

    /**
     * 复制
     *
     * @param sourceObj
     * @param targetClass
     * @param <T>
     * @param <S>
     * @return
     */
    public static <T, S> T copy(S sourceObj, Class<T> targetClass) {
        if (sourceObj == null) {
            return null;
        }
        String tempString = JSONObject.toJSONString(sourceObj, true);

        // 双引号替换成单引号
        tempString = tempString.replaceAll("\"", "\'");

        return JSONObject.parseObject(tempString, targetClass);
        //return JSON.parseObject(JSON.toJSONString(sourceObj), targetClass);
        //return JSON.parseObject(JSON.toJSONString(sourceObj, true), targetClass);
    }

    /**
     * 复制集合
     *
     * @param sourceList
     * @param targetClass
     * @param <T>
     * @return
     */
    public static <T> List<T> copyList(List<? extends Object> sourceList, Class<T> targetClass) {
        if (CollectionUtils.isEmpty(sourceList)) {
            return new ArrayList();
        }
        String tempString = JSON.toJSONString(sourceList);
        // 双引号替换成单引号
        tempString = tempString.replaceAll("\"", "\'");
        return JSON.parseArray(tempString, targetClass);
        //return JSON.parseArray(JSON.toJSONString(sourceList), targetClass);
    }

    /**
     * @param source 要拷贝的对象
     * @return
     * @Description <p>获取到对象中属性为null的属性名  </P>
     */
    private static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    /**
     * 复制非空的属性
     *
     * @param oldItem 旧数据
     * @param newItem 老数据
     * @param <T>
     */
    public static <T> void copyProperties(T oldItem, T newItem) {
        BeanUtils.copyProperties(newItem, oldItem, getNullPropertyNames(oldItem));
    }

}
